package com.knowledgeqa.system.controller;

import com.knowledgeqa.system.entity.User;
import com.knowledgeqa.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        boolean success = userService.register(user);
        result.put("success", success);
        result.put("message", success ? "注册成功" : "注册失败，用户名、手机号或邮箱已存在");
        return ResponseEntity.ok(result);
    }

    /**
     * 删除用户（注销）
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户ID是否有效
            if (id == null) {
                result.put("success", false);
                result.put("message", "用户ID无效，请重新登录后再试");
                return ResponseEntity.ok(result);
            }

            boolean success = userService.deleteUser(id);
            result.put("success", success);
            result.put("message", success ? "用户删除成功" : "用户删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginInfo) {
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");

        Map<String, Object> result = new HashMap<>();
        try {
            User user = userService.login(username, password);
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("user", user);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info/{id}")
    public ResponseEntity<Map<String, Object>> getUserInfo(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.findById(id);
        if (user != null) {
            result.put("success", true);
            result.put("user", user);
        } else {
            result.put("success", false);
            result.put("message", "用户不存在");
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateUser(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        boolean success = userService.update(user);
        result.put("success", success);
        result.put("message", success ? "更新成功" : "更新失败");
        return ResponseEntity.ok(result);
    }

    /**
     * 更新用户头像
     */
    @PutMapping("/avatar")
    public ResponseEntity<Map<String, Object>> updateAvatar(@RequestBody Map<String, Object> avatarInfo) {
        Long userId = Long.valueOf(avatarInfo.get("userId").toString());
        String base64Image = (String) avatarInfo.get("avatar");

        Map<String, Object> result = new HashMap<>();
        try {
            String avatarPath = userService.updateAvatar(userId, base64Image);
            result.put("success", true);
            result.put("message", "头像更新成功");
            result.put("avatarPath", avatarPath);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "头像更新失败：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户金币余额
     */
    @GetMapping("/coin/{id}")
    public ResponseEntity<Map<String, Object>> getCoinBalance(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        Integer balance = userService.getCoinBalance(id);
        result.put("success", true);
        result.put("balance", balance);
        return ResponseEntity.ok(result);
    }
}